package com.ty.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;

/**
 * Web工具类
 *
 * @Author Tommy
 * @Date 2022/1/27
 */
@Slf4j
public class WebUtil {

    /**
     * 是否为异步请求
     *
     * @return boolean
     */
    public static boolean isAjax() {
        final String requestType = getHttpRequest().getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(requestType);
    }

    /**
     * 禁用HTTP缓存
     *
     * @param response
     */
    public static void disableHttpCache(HttpServletResponse response) {

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragrma", "no-cache");
        response.setDateHeader("Expires", 0);
    }

    /**
     * 发送错误状态
     *
     * @param response
     * @param statusCode
     */
    public static void sendError(HttpServletResponse response, int statusCode) throws IOException {
        response.sendError(statusCode);
    }

    /**
     * 重定向到指定URL
     *
     * @param url
     * @param response
     */
    public static void redirect(String url, HttpServletResponse response) {

        if (StringUtils.isNotBlank(url)) {
            try {
                response.sendRedirect(url);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 跳转到指定URL
     *
     * @param url
     * @param request
     */
    public static void forward(String url, HttpServletRequest request, HttpServletResponse response) {

        if (StringUtils.isNotBlank(url)) {
            try {
                request.getRequestDispatcher(url).forward(request, response);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 获取HttpServletRequest
     */
    public static HttpServletRequest getHttpRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }

    /**
     * 获取Http Session
     */
    public static HttpSession getHttpSession() {
        return getHttpRequest().getSession();
    }

    /**
     * 获取User Agent
     *
     * @return String
     */
    public static String getUserAgent() {
        return getHttpRequest().getHeader("User-Agent");
    }
}
